package com.wangdong.mijiqiqi.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by liusaisai on 2016/6/12.
 */
public class Tools {
    /**
     * 判断网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetWorkAvailable(Context context) {
        boolean result = false;
        ConnectivityManager cManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cManager.getActiveNetworkInfo() != null) {
            result = true;
        }
        return result;
    }

    /**
     * 获取ip地址
     *
     * @return
     */
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
        }
        return null;
    }

    /**
     * 转换kb Mb Gb
     */
    public static String byteFormat(long _byte) {
        if ((_byte >> 10) < 1) {
            return _byte + "b";
        } else if ((_byte >> 20) < 1) {
            return String.format("%.2f", (float) _byte / (1024)) + "K";
        } else if ((_byte >> 30) < 1) {
            return String.format("%.2f", (float) _byte / (1024 * 1024)) + "M";
        }
        return String.format("%.2f", (float) _byte / (1024 * 1024 * 1024)) + "G";
    }

    /**
     * 把数据源HashMap转换成json
     *
     * @param map
     */
    public static String mapToJson(Map<String, String> map) {
        String strResult = "";
        StringBuffer sbResult = new StringBuffer();
        sbResult.append("{");
        for (Iterator<?> it = map.entrySet().iterator(); it.hasNext(); ) {
            Map.Entry<?, ?> e = (Map.Entry<?, ?>) it.next();
            if (e.getValue().toString().startsWith("{") || e.getValue().toString().startsWith("[")) {
                sbResult.append("\"").append(e.getKey()).append("\":").append(e.getValue()).append(",");
            } else {
                sbResult.append("\"").append(e.getKey()).append("\":\"").append(e.getValue()).append("\",");
            }
        }
        strResult = sbResult.toString();
        strResult = strResult.substring(0, strResult.lastIndexOf(","));
        strResult += "}";
        return strResult;
    }

    /*
     * json解析
     *
     * @param json json字符串
     *
     * @param cls 解析后的对应类
     *
     * @return objcet
     */
    public static <T> T fromJsonToObj(String json, Class<T> cls) {
        T result = null;
        try {
            Gson gson = new Gson();
            result = (T) gson.fromJson(json, cls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /*
     * json解析
     *
     * @param json json字符串
     *
     * @param Type listType = new TypeToken<LinkedList<T>>() {}.getType();
     * 需要将T替换成具体的类，否则返回LinkedHashMap对象
     *
     * @return List
     */
    public static <T> List<T> fromJsonToList(String json, Type listType) {
        List<T> result = null;
        try {
            Gson gson = new Gson();
            result = gson.fromJson(json, listType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /*
     * 生成json
     *
     * @param object
     *
     * @return
     */
    public static String toJson(Object object) {
        String result = null;
        try {
            result = (new Gson()).toJson(object);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    // SHA1 加密
    public static String encryptToSHA(String info) {
        byte[] digesta = null;
        try {
            // 得到一个SHA-1的消息摘要
            MessageDigest alga = MessageDigest.getInstance("SHA-1");
            // 添加要进行计算摘要的信息
            alga.update(info.getBytes());
            // 得到该摘要
            digesta = alga.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 将摘要转为字符串
        String rs = byte2hex(digesta);
        return rs;
    }

    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs;
    }

    // MD5 加密
    public static String getMD5(String info) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(info.getBytes("UTF-8"));
            byte[] encryption = md5.digest();

            StringBuffer strBuf = new StringBuffer();
            for (int i = 0; i < encryption.length; i++) {
                if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
                    strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
                } else {
                    strBuf.append(Integer.toHexString(0xff & encryption[i]));
                }
            }
            return strBuf.toString();
        } catch (NoSuchAlgorithmException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    // 获取系统当前时间
    public static String getCurrentTime() {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = dateFormat.format(now);
        return currentTime;
    }

    /**
     * 获得当前的网络连接状态
     *
     * @param context
     * @return
     */
    public static String getCurrentNetwork(Context context) {
        String strNetworkType = "other";
        NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE))
                .getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                strNetworkType = "wifi";
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                String _strSubTypeName = networkInfo.getSubtypeName();
                // TD-SCDMA networkType is 17
                int networkType = networkInfo.getSubtype();
                switch (networkType) {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN: // api<8 : replace by
                        // 11
                        strNetworkType = "2g";
                        break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B: // api<9 : replace by
                        // 14
                    case TelephonyManager.NETWORK_TYPE_EHRPD: // api<11 : replace by
                        // 12
                    case TelephonyManager.NETWORK_TYPE_HSPAP: // api<13 : replace by
                        // 15
                        strNetworkType = "3g";
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE: // api<11 : replace by
                        // 13
                        strNetworkType = "4g";
                        break;
                    default:
                        // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
                        if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA")
                                || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                            strNetworkType = "3g";
                        } else {
                            strNetworkType = _strSubTypeName;
                        }

                        break;
                }
            }
        }
        return strNetworkType;
    }

    /**
     * 隐藏软键盘
     */
    public static void hideSoftKeyboard(Activity activity) {
        try {
            InputMethodManager inputMethodManager = (InputMethodManager) activity
                    .getSystemService(Activity.INPUT_METHOD_SERVICE);
            if (inputMethodManager.isActive())
                inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 防止按键双击
     *
     * @param view
     */
    public static void preventDoubleClick(final View view) {
        view.setEnabled(false);

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                view.setEnabled(true);
            }
        }, 1000);
    }

    public static String getTimeHint(long createTime) {
        long time = System.currentTimeMillis() / 1000 - createTime;
        int year = (int) (time / (60 * 60 * 24 * 365));
        int month = (int) (time / (60 * 60 * 24 * 30));
        int day = (int) (time / (60 * 60 * 24));
        int hour = (int) (time / (60 * 60));
        int minute = (int) (time / 60);
        if (year > 0) {
            return year + "年前";
        } else if (month > 0) {
            return month + "月前";
        } else if (day > 0) {
            return day + "天前";
        } else if (hour > 0) {
            return hour + "小时前";
        } else if (minute > 0) {
            return minute + "分钟前";
        } else {
            return "刚刚";
        }

    }

    /**
     * 2  * 获取版本号
     * 3  * @return 当前应用的版本号
     * 4
     */
    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
